package cn.dogger.easyboot.common.util;

import cn.hutool.core.util.NumberUtil;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 客户端工具类

 */
public class ServletUtils {
    /**
     * 获取String参数
     */
    public static String getParameter(String name){
        return getRequest().getParameter(name);
    }


    /**
     * 获取request
     */
    public static HttpServletRequest getRequest(){
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse(){
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取request中的int参数
     * @param name 字段名称
     * @return 整数或null
     */
    public static Integer getRequestInt(String name){
        String str = getRequest().getParameter(name);
        if(NumberUtil.isInteger(str)){
            return Integer.parseInt(str);
        }else{
            return null;
        }
    }

    /**
     * 获取session
     */
    public static HttpSession getSession(){
        return getRequest().getSession();
    }

    public static ServletRequestAttributes getRequestAttributes(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }
}
